package com.tjbank.cssys.web.util;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class TimeUtils {
    /**
     * 获取当月最后一天数据
     * @param endTime
     * @return
     * @throws ParseException
     */
    public String getLastTime(String endTime) throws ParseException {
        String[] startSplit = endTime.split("-");
        int year = Integer.parseInt(startSplit[0]);
        int month = Integer.parseInt(startSplit[1]);
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR,year);
        calendar.set(Calendar.MONTH,month);
        int minimum = calendar.getMinimum(Calendar.DATE);
        calendar.set(Calendar.DAY_OF_MONTH,minimum-1);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return  simpleDateFormat.format(calendar.getTime());
    }
    /**
     * 获取当月最后一天数据
     * @param startTime
     * @return
     * @throws ParseException
     */
    public String getFirstTime(String startTime) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parse = simpleDateFormat.parse(startTime);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(parse);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        return simpleDateFormat.format(calendar.getTime());
    }


    /**
     * 获取两个日期之间的所有日期
     * @param startTime
     * @param endTime
     * @return
     * @throws ParseException
     */
    public List<String> getBetweenDays(String startTime, String endTime) throws ParseException {
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            List<String> result = new ArrayList<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date startTimeParse = simpleDateFormat.parse(startTime);
            Date endTimeParse = simpleDateFormat.parse(endTime);
            Calendar startCalendar = Calendar.getInstance();
            startCalendar.setTime(startTimeParse);
            startCalendar.add(Calendar.DAY_OF_YEAR,1);
            Calendar endCalendar = Calendar.getInstance();
            endCalendar.setTime(endTimeParse);
            result.add(simpleDateFormat.format(startTimeParse));
            while (startCalendar.before(endCalendar)) {
                result.add(simpleDateFormat.format(startCalendar.getTime()));
                startCalendar.add(Calendar.DAY_OF_YEAR,1);
            }
            return result;
        } else {
            return null;
        }
    }
}
